package hongcaosp.app.android.user.settings.info;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.AddressPicker;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.util.ConvertUtils;
import hongcaosp.app.android.R;
import hongcaosp.app.android.common.BaseAdapter;
import hongcaosp.app.android.common.BaseHolder;
import hongcaosp.app.android.login.UserToken;
import hongcaosp.app.android.user.settings.info.iview.UpdateUserInfoIView;
import hongcaosp.app.android.user.settings.info.presenter.UpdateUserInfoPresenter;
import xlj.lib.android.base.component.BaseActivity;
import xlj.lib.android.base.toastcompat.ToastManager;
import xlj.lib.android.base.utils.DensityUtils;
import xlj.lib.android.base.view.OnRecycleItemClickListener;

/**
 * 修改用户资料
 */
public class UpdateUserInfoActivity extends BaseActivity implements UpdateUserInfoIView {

    public static void launcher(Activity activity,int type,String old) {
        Intent intent = new Intent(activity,UpdateUserInfoActivity.class);
        intent.putExtra("type",type);
        intent.putExtra("old",old);
        activity.startActivityForResult(intent,1);
    }

    private TextView tv_title,tv_label,tv_hint,tv_content;
    private EditText et_content;

    private List<JSONObject> list_sex = new ArrayList<>();
    private BaseAdapter<JSONObject> adpater;

    private int type;
    private UpdateUserInfoPresenter presenter;

    private int sexValue = 1;

    @Override
    protected void initData(Intent intent) {
        type = intent.getIntExtra("type",-1);
        switch (type) {
            case 1:
                //修改昵称
            case 2:
                //修改签名
            case 6:
                //修改学校
                findViewById(R.id.ll_container_one).setVisibility(View.VISIBLE);
                tv_label = findViewById(R.id.tv_label);
                tv_hint = findViewById(R.id.tv_hint);
                et_content = findViewById(R.id.et_content);
                et_content.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                        int max = (int) tv_hint.getTag();
                        tv_hint.setText(charSequence.length() + "/" + max);
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {

                    }
                });
                String title = "昵称";
                String label = "我的昵称";
                String content = "请填写昵称";
                int maxLength = 20;
                if (type == 2) {
                    title = "修改签名";
                    label = "个性签名";
                    content = "请填写个性签名更容易获得别人关注哦";
                    maxLength = 40;
                }
                if (type == 6) {
                    title = "学校";
                    label = "我的学校";
                    content = "请填写学校";
                    maxLength = 20;
                }
                tv_title.setText(title);
                tv_label.setText(label);
                tv_hint.setTag(maxLength);
                tv_hint.setText("0/" + tv_hint.getTag().toString());
                et_content.setHint(content);
                et_content.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
                break;
            case 3:
                //修改性别
                tv_title.setText("性别");
                JSONObject obj = new JSONObject();
                obj.put("content","男");
                obj.put("status",0);
                obj.put("value",1);
                list_sex.add(obj);

                obj = new JSONObject();
                obj.put("content","女");
                obj.put("status",0);
                obj.put("value",2);
                list_sex.add(obj);

                obj = new JSONObject();
                obj.put("content","不显示");
                obj.put("status",0);
                obj.put("value",0);
                list_sex.add(obj);
                findViewById(R.id.ll_container_two).setVisibility(View.VISIBLE);

                adpater = new BaseAdapter<JSONObject>() {
                    @NonNull
                    @Override
                    public BaseHolder<JSONObject> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                        return new UserinfoSexHolder(LayoutInflater.from(UpdateUserInfoActivity.this).inflate(R.layout.item_userinfo_sex, parent, false), new OnRecycleItemClickListener() {
                            @Override
                            public void onItemClick(int position) {
                                for(JSONObject obj:list_sex) {
                                    obj.put("status",0);
                                }
                                list_sex.get(position).put("status",1);
                                sexValue = list_sex.get(position).getIntValue("value");
                                adpater.notifyDataSetChanged();
                            }

                            @Override
                            public void onItemLongClick(int position) {

                            }
                        });
                    }
                };
                adpater.addData(list_sex);
                RecyclerView rv_sex = findViewById(R.id.rv_sex);
                rv_sex.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
                rv_sex.setAdapter(adpater);
                break;
            case 4:
                //修改生日
            case 5:
                tv_title.setText(type == 4 ? "生日" : "地址");

                findViewById(R.id.ll_container_three).setVisibility(View.VISIBLE);
                ((TextView)findViewById(R.id.tv_three_label)).setText(type == 4 ? "我的生日" : "我的地址");

                tv_content = findViewById(R.id.tv_content);
                tv_content.setHint(type == 4 ? "请选择生日" : "请选择地址");
                tv_content.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (type == 4) {
                            final DatePicker picker =  new DatePicker(UpdateUserInfoActivity.this);
                            picker.setCanceledOnTouchOutside(true);
                            picker.setUseWeight(true);
                            picker.setTopPadding(DensityUtils.dip2px(UpdateUserInfoActivity.this,10));
                            picker.setRangeStart(1990, 1, 1);
                            picker.setRangeEnd(2020, 1, 1);
                            picker.setSelectedItem(1995, 1, 1);
                            picker.setResetWhileWheel(false);
                            picker.setContentPadding(DensityUtils.dip2px(UpdateUserInfoActivity.this,5),DensityUtils.dip2px(UpdateUserInfoActivity.this,5));
                            picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                                @Override
                                public void onDatePicked(String year, String month, String day) {
                                    tv_content.setText(year + "-" + month + "-" + day);
                                }
                            });
                            picker.show();
                        } else {
                            try {
                                ArrayList<Province> data = new ArrayList<>();
                                String json = ConvertUtils.toString(getAssets().open("city.json"));
                                data.addAll(JSON.parseArray(json, Province.class));
                                AddressPicker picker = new AddressPicker(UpdateUserInfoActivity.this, data);
                                picker.setShadowVisible(true);
                                picker.setTextSizeAutoFit(false);
                                picker.setHideProvince(false);
//                                picker.setTextColor(R.color.t);
                                picker.setContentPadding(DensityUtils.dip2px(UpdateUserInfoActivity.this,5),DensityUtils.dip2px(UpdateUserInfoActivity.this,5));
                                picker.setOnAddressPickListener(new AddressPicker.OnAddressPickListener() {
                                    @Override
                                    public void onAddressPicked(Province province, City city, County county) {
                                        String address = province.getName() + city.getName() + county.getName();
                                        if (province.getName().equals(city.getName())) {
                                            address = city.getName() + county.getName();
                                        }
                                        tv_content.setText(address);
                                    }
                                });
                                picker.show();
                            } catch (Exception e) {
                            }
                        }
                    }
                });
                //修改地区
                break;
        }
    }

    @Override
    protected void initView() {
        presenter = new UpdateUserInfoPresenter(this);
        tv_title = findViewById(R.id.tv_title);
        findViewById(R.id.back_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == 3) {
                    if (sexValue == -1) {
                        ToastManager.getInstance().showToast("请选择性别");
                        return;
                    }
                    presenter.save("" + sexValue,type);
                } else if (type == 4 || type == 5) {
                    String value = tv_content.getText().toString();
                    if (TextUtils.isEmpty(value)) {
                        ToastManager.getInstance().showToast(type == 4 ? "生日还没有选择噢" : "地址还没有选择噢",Toast.LENGTH_SHORT,Gravity.CENTER);
                        return;
                    }
                    presenter.save(value,type);
                } else {
                    String value = et_content.getText().toString();
                    if (TextUtils.isEmpty(value)) {
                        ToastManager.getInstance().showToast("什么都没有输入噢",Toast.LENGTH_SHORT,Gravity.CENTER);
                        return;
                    }
                    presenter.save(value,type);
                }

            }
        });
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_update_userinfo;
    }

    @Override
    public void saveResult(String msg, int code) {
        if (code == 0) {
            if (type == 1) {
                UserToken.getDefault().getUser().setNickName(et_content.getText().toString());
            } else if (type == 2) {
                UserToken.getDefault().getUser().setUserComment(et_content.getText().toString());
            } else if (type == 3) {
                UserToken.getDefault().getUser().setSex(sexValue);
            } else if (type == 4) {
                try {
                    UserToken.getDefault().getUser().setBirthday(new SimpleDateFormat("yyyy-MM-dd",Locale.CHINA).parse(tv_content.getText().toString()).getTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else if (type == 5) {
                UserToken.getDefault().getUser().setLocality(tv_content.getText().toString());
            } else if (type == 6) {
                UserToken.getDefault().getUser().setSchoolName(et_content.getText().toString());
            }
            UserToken.getDefault().save();
            setResult(RESULT_OK);
            finish();
            return;
        }
        ToastManager.getInstance().showToast(msg);
    }
}
